<template>
  <a-upload
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :action="baseURL"
    :before-upload="beforeUpload"
    @change="handleChange"
    :headers="headers"
  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" class="upload-image" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">
        {{ $t('Upload') }}
      </div>
    </div>
  </a-upload>
</template>
<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/utils/constants'
export default {
  data() {
    return {
      loading: false,
      imageUrl: '',
      baseURL: 'https://org/stock/file/upload',
      headers: {
        token: storage.get(ACCESS_TOKEN)
      }
    }
  },
  methods: {
    handleChange(info) {
      console.log(info, 'status')
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        this.loading = false
        if (info.file.response && info.file.response.code === '0000') {
          this.imageUrl = info.file.response.data
          this.$emit('update', info.file.response.data)
        } else if (info.file.response && info.file.response.code !== '0000') {
          this.$notification.error({
            message: 'Error',
            description: info.file.response.msg || 'system error'
          })
        }
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error(this.$t('You can only upload JPG file') + '!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error(this.$t('Image must smaller than 2MB') + '!')
      }
      return isJpgOrPng && isLt2M
    }
  }
}
</script>
<style>
.avatar-uploader > .ant-upload,
.upload-image {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
